using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml.Linq;

namespace TwitterClient
{
	public class TwitterProxy
	{	
		public List<Tweet> RetrieveFriendUpdates(int updateCt_)
		{
			if (updateCt_ > MAX_UPDATES_PER_REQUEST)
				throw new ArgumentOutOfRangeException("updateCt_", String.Format("You may not retrieve more than {0} updates per request.", MAX_UPDATES_PER_REQUEST));
			
			return XDocument.Parse(BaseClient.DownloadString(String.Format(UPDATE_REQUEST_URL, updateCt_)))
				   .Descendants("status")
				   .Select(e => new Tweet(e))
				   .ToList();
		}
		
		public string AccountUserName { get; set; }
		public string AccountPassword { get; set; }
		
		private WebClient BaseClient
		{
			get
			{
				if (_baseClient == null)
				{
					if (String.IsNullOrEmpty(AccountUserName))
						throw new ApplicationException("Account user name is required; unable to proceed.");
					
					if (String.IsNullOrEmpty(AccountPassword))
						throw new ApplicationException("Account password is required; unable to proceed.");
					
					_baseClient = new WebClient { Credentials = new NetworkCredential(AccountUserName, AccountPassword) };
				}
				
				return _baseClient;
			}
		}
		
		private WebClient _baseClient;
		
		private const int MAX_UPDATES_PER_REQUEST = 200;
		private const string UPDATE_REQUEST_URL = "http://twitter.com/statuses/friends_timeline.xml?count={0}";
	}
}
